<template>
  <div class="problem-container">
    <a-card class="problem-card">
      <template #title>
        <div class="card-title">
          <span>题目列表</span>
        </div>
      </template>

      <a-form :model="searchForm" layout="inline" class="search-form">
        <a-form-item field="searchText" label="搜索">
          <a-input
            v-model="searchForm.searchText"
            placeholder="搜索题目标题"
            allow-clear
            @press-enter="handleSearch"
          />
        </a-form-item>
        <a-form-item field="difficulty" label="难度">
          <a-select
            v-model="searchForm.difficulty"
            placeholder="选择难度"
            allow-clear
            @change="handleSearch"
          >
            <a-option value="EASY">简单</a-option>
            <a-option value="MEDIUM">中等</a-option>
            <a-option value="HARD">困难</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="tags" label="标签">
          <a-select
            v-model="searchForm.tags"
            placeholder="选择标签"
            multiple
            allow-clear
            @change="handleSearch"
          >
            <a-option v-for="tag in tagList" :key="tag.id" :value="tag.id">
              {{ tag.name }}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <template #icon><icon-search /></template>
              搜索
            </a-button>
            <a-button @click="handleReset">
              <template #icon><icon-refresh /></template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <a-table
        :data="problemList"
        :loading="loading"
        :pagination="pagination"
        @page-change="onPageChange"
        @sorter-change="handleSorterChange"
      >
        <template #columns>
          <a-table-column title="题号" data-index="id" :width="80" />
          <a-table-column title="题目" data-index="title">
            <template #cell="{ record }">
              <a-link @click="handleView(record.id)">
                {{ record.title }}
              </a-link>
            </template>
          </a-table-column>
          <a-table-column title="难度" data-index="difficulty" :width="100">
            <template #cell="{ record }">
              <a-tag :color="getDifficultyColor(record.difficulty)">
                {{ getDifficultyText(record.difficulty) }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column 
            title="提交次数" 
            data-index="submitNum" 
            :width="100"
          />
          <a-table-column 
            title="通过率" 
            data-index="acceptedNum" 
            :width="120"
            :sortable="{
              sortDirections: ['ascend', 'descend'],
            }"
          >
            <template #cell="{ record }">
              {{ getAcceptRate(record) }}
            </template>
          </a-table-column>
          
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Message } from '@arco-design/web-vue'
import {
  IconSearch,
  IconRefresh,
} from '@arco-design/web-vue/es/icon'
import type { FormInstance } from '@arco-design/web-vue'
import {
  getProblemListPageVoApi,
} from '@/api/problem/problem'
import { useTagStore } from '@/stores/tag'

const router = useRouter()
const tagStore = useTagStore()

// 标签列表
const tagList = ref<API.Tag[]>([])

// 搜索表单
const searchForm = reactive<API.ProblemQueryRequest>({
  current: 1,
  pageSize: 10,
  searchText: '',
  difficulty: undefined,
  tags: [],
  sortField: undefined,
  sortOrder: undefined
})

// 表格数据
const problemList = ref<API.ProblemVO[]>([])
const loading = ref(false)

// 分页配置
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10
})

// 表单相关
const formRef = ref<FormInstance>()
const formData = reactive<API.ProblemAddRequest>({
  title: '',
  content: '',
  difficulty: '简单',
  judgeConfig: {
    time_limit: 1000,
    memory_limit: 128
  },
  judgeCaseList: []
})

// 表单校验规则
const rules = {
  title: [{ required: true, message: '请输入题目名称' }],
  content: [{ required: true, message: '请输入题目内容' }],
  difficulty: [{ required: true, message: '请选择难度' }]
}

// 获取标签列表
const fetchTagList = async () => {
  try {
    await tagStore.fetchAllTags()
    tagList.value = tagStore.tagList
  } catch (error) {
    Message.error('获取标签列表失败')
  }
}

// 获取题目列表
const fetchProblemList = async () => {
  loading.value = true
  try {
    const res = await getProblemListPageVoApi(searchForm)
    problemList.value = res.data?.records || []
    pagination.total = res.data?.total || 0
  } catch (error) {
    Message.error('获取题目列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  searchForm.current = 1
  fetchProblemList()
}

// 排序变化
const handleSorterChange = (dataIndex: string, direction: 'ascend' | 'descend' | '') => {
  searchForm.sortField = direction ? dataIndex : undefined
  searchForm.sortOrder = direction
  fetchProblemList()
}

// 重置
const handleReset = () => {
  searchForm.searchText = ''
  searchForm.difficulty = undefined
  searchForm.tags = []
  searchForm.sortField = undefined
  searchForm.sortOrder = undefined
  handleSearch()
}

// 分页变化
const onPageChange = (current: number) => {
  searchForm.current = current
  fetchProblemList()
}

// 查看题目
const handleView = (id: number) => {
  router.push(`/problem/${id}`)
}

// 获取难度标签颜色
const getDifficultyColor = (difficulty: string) => {
  switch (difficulty) {
    case 'EASY':
      return 'green'
    case 'MEDIUM':
      return 'orange'
    case 'HARD':
      return 'red'
    default:
      return 'blue'
  }
}

// 获取难度文本
const getDifficultyText = (difficulty: string) => {
  switch (difficulty) {
    case 'EASY':
      return '简单'
    case 'MEDIUM':
      return '中等'
    case 'HARD':
      return '困难'
    default:
      return difficulty
  }
}

// 计算通过率
const getAcceptRate = (record: API.ProblemVO) => {
  if (record.submitNum === 0) return '0%'
  return `${((record.acceptedNum / record.submitNum) * 100).toFixed(1)}%`
}

onMounted(() => {
  fetchTagList()
  fetchProblemList()
})
</script>

<style scoped>

.problem-card {
  max-height: calc(100vh - 140px);
}

.card-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.judge-case {
  margin-bottom: 16px;
  padding: 16px;
  border: 1px solid var(--color-border);
  border-radius: 4px;
}
</style> 